<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="Keywords" content="">
	<meta name="Description" content="">
	<title>0609-JS作业-随机生成拼图-螺旋</title>
	<style type="text/css">
		body{margin: 0;background-color: #666;}
		.wrap{
			margin: 0 auto;
		}
		.pic{
			cursor: pointer;
		}
		.jigsaw{
			position: relative;
		}
		.pic,.jigsaw i{
			background: url("images/3.jpg") no-repeat;
		}
		.jigsaw i{
			position: absolute;
			transition: 1s;
		}
	</style>
</head>
<body>
	<section class="wrap">
		<div class="pic"></div>
		<div class="jigsaw"></div>
	</section>
</body>
<script>
	var oWarp = document.getElementsByClassName('wrap')[0],
        oPic = document.getElementsByClassName('pic')[0],
		oJig = document.getElementsByClassName('jigsaw')[0],
        oJigI = oJig.getElementsByTagName('i'),
		oWH = {wid:800,hgt:450},//图片尺寸可变
        oRC = {row:5,col:8},//拼图数量可变
        oPwh = {wid:oWH.wid/oRC.col,hgt:oWH.hgt/oRC.row},//每块拼图的宽高
        aPics = [],swit = true,oI;

    //生成各个标签的宽高等属性
    oWarp.style.width = oWH.wid+'px';
    oWarp.style.height = oWH.hgt*2+'px';
    oPic.style.width = oWH.wid+'px';
    oPic.style.height = oWH.hgt+'px';
    oPic.style.backgroundSize = `${oWH.wid}px ${oWH.hgt}px`;
    oJig.style.width = oWH.wid+'px';
    oJig.style.height = oWH.hgt+'px';

    //生成li 设置每个li的宽高 背景图片的大小和位置
    for(var j=0;j<oRC.row;j++){
        for(var k=0;k<oRC.col;k++){
            oI = document.createElement("i");
            oI.style.width = oPwh.wid+'px';
            oI.style.height = oPwh.hgt+'px';
            oI.style.backgroundPosition = `${-k*oPwh.wid}px ${-j*oPwh.hgt}px`;
            oI.style.backgroundSize = `${oWH.wid}px ${oWH.hgt}px`;
            oI.style.left = k*oPwh.wid+'px';
            oI.style.top = j*oPwh.hgt+'px';
            oJig.appendChild(oI);
        }
    }
    
    //生成随机拼图
    fnRdm();
	function fnRdm(){
        aPics = [];
        //将每个li进行随机编号 然后将其定位数值与编号一一对应 装进数组
        for(var i=0;i<oRC.row*oRC.col;i++){
            aPics.push({
                num:i,
                num2:parseInt(Math.random()*100),
                posl:oJigI[i].style.left,
                post:oJigI[i].style.top
            })
        }
        //将原aPics的元素按照num2数值从小到大排序 生成随机拼图
	    aPics = aPics.sort(function(a,b){
	        return a.num2-b.num2;
	    });
        fnCre();
    }

    //生成拼图位置
    function fnCre(){
        for(var i=0;i<oRC.row*oRC.col;i++){
            oJigI[i].style.left = aPics[i].posl;
            oJigI[i].style.top = aPics[i].post;
        }
    }
    
    //点击上面大图 将下面的拼图自动归位 再点击一次 重新生成随机拼图
    oPic.onclick = function(){
	    if(swit){
            aPics = aPics.sort(function(a,b){
                return a.num-b.num;
            });
            fnCre();
            swit = false;
	    }else{
            fnRdm();
            swit = true;
	    }
    }
</script>
</html>